package com.lightsh.widgetdemo;

import android.app.Activity;
import android.appwidget.AppWidgetManager;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;

public class ConfigureActivity extends Activity{

	private static final String TAG = "com.lightsh.widgetdeom.ConfigureActivity";
	private int mAppWidgetId;
	
	private static final int MSG_FINISH = 1;
	
	private Handler mHandler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			switch(msg.what){
			case MSG_FINISH:
				Log.e(TAG, "MSG_FINISH");
				Intent resultValue = new Intent();
				resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
				setResult(RESULT_CANCELED, resultValue);
				ConfigureActivity.this.finish();
				break;
			default:
				super.handleMessage(msg);
			}
		}
		
	};
	
	
	@Override
	public void onBackPressed() {
//		setResult(RESULT_CANCELED);
		super.onBackPressed();
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.configure_activity);
		
		Intent intent = getIntent();
		Bundle extras = intent.getExtras();
		if (extras != null) {
		    mAppWidgetId = extras.getInt(
		            AppWidgetManager.EXTRA_APPWIDGET_ID, 
		            AppWidgetManager.INVALID_APPWIDGET_ID);
		}
		Log.e(TAG, "mAppWidgetId:" + mAppWidgetId);
		
		// 先设置取消值，避免用户按取消时，没有删除该widget(当用户点击home键时该activity会执行destroy并且不会返回结果给shell，造成widget丢失!!!)
		Intent resultValue = new Intent();
		resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
		setResult(RESULT_CANCELED, resultValue);
		
		Button btnCancel = (Button)findViewById(R.id.btnCancel);
		btnCancel.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				finish();
			}
		});
		
		Button btnOk = (Button)findViewById(R.id.btnOK);
		btnOk.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				Intent resultValue = new Intent();
				resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
				setResult(RESULT_OK, resultValue);
				finish();
			}
		});
	}

	@Override
	protected void onPause() {
		Log.e(TAG, "onPause");
		super.onPause();
	}

	@Override
	protected void onStop() {
		Log.e(TAG, "onStop");
		super.onStop();
	}

	@Override
	protected void onDestroy() {
		Log.e(TAG, "onDestroy");
		super.onDestroy();
	}

}
